 
let userListModule = (function () { 
    let $deleteAll = $('.deleteAll'),
        $selectBox = $('.selectBox'),
        $searchInp = $('.searchInp'),
        $tableBox = $('.tableBox'),
        $tbody = $tableBox.find('tbody'),
        $checkAll=$('#checkAll'),
        $checkList = null
 
    
    // 绑定部门
    async function bindDepart() { 
        let result = await queryDepart()
        if (result.code == 0) {
            let str=``
            result.data.forEach(item => {
                str+=`<option value="${item.id}">${item.name}</option>`
            })
            $selectBox.append(str)
        } 
    }
    
    // 绑定列表
    async function bindHtml() {
        let result,
            params = {
                departmentId: $selectBox.val(),
                search:$searchInp.val()
            }
        result = await axios.get('/user/list', {
            params
        })
        if (result.code != 0) return
        let str = ``
        result.data.forEach(item => { 
            let {id,name,sex,email,phone,departmentId,department,jobId,job,desc} = item
            str+=`<tr>
                <td class="w3"><input type="checkbox" userid=${id}></td>
                <td class="w10">${name}</td>
                <td class="w5">${sex==0?'男':'女'}</td>
                <td class="w10">${department}</td>
                <td class="w10">${job}</td>
                <td class="w15">${email}</td>
                <td class="w15">${phone}</td>
                <td class="w20">${desc}</td>
                <td class="w12" userid=${id}>
                    <a href="javascript:;" class="btnEdit">编辑</a>
                    <a href="javascript:;" class="btnDelete">删除</a>
                    <a href="javascript:;" class="btnReset">重置密码</a>
                </td>
            </tr>` 
        }) 
        $tbody.html(str) 
        $checkList = $tbody.find('input[type="checkbox"]')
    }

    // 触发数据的重新绑定
    function searchHandle() {
        $selectBox.change(bindHtml)
        $searchInp.on('keydown', ev => {
            if (ev.keyCode === 13) {
                bindHtml()
            }
        })
    }
    // 基于时间委托处理操作
    function delegate() {
        $tbody.click(async ev => {
            let target = ev.target,
                $target = $(target)
            let userid= $target.parent().attr('userid')
            if (target.className === 'btnEdit') { 
                window.location.href='useradd.html?userid='+userid
                return
            }
            if (target.className === 'btnDelete') {
                let flag=confirm(`确定要删除编号为[${userid}]的信息吗？`)
                if (!flag) return
                let result = await axios.get('user/delete', { params: { userId: userid } })
                if (result.code == 0) {
                    alert('删除成功')
                    // 删除这条数据
                    $target.parent().parent().remove()
                    $checkList = $tbody.find('input[type="checkbox"]')
                    return
                }
                alert('删除失败')
                return
            }
            if (target.className === 'btnReset') {
                let flag = confirm(`确定要重置编号为[${userid}]的密码吗？`)
                let result = await axios.post('user/resetpassword', {  userId: userid }) 
                if (!flag) return
                if (result.code == 0) {
                    alert('重置成功') 
                    return
                }
                alert('删除失败')
                return
            }

        })
    }

    //全选处理
    function selectHandle() {
        $checkAll.click(ev => {
            let checked = $checkAll.prop('checked')
            $checkList.prop('checked',checked)
        })
        $tbody.click(ev => {
            let target = ev.target,
                TagName = target.tagName
            if (TagName = 'INPUT') {
                let flag = true
                Array.prototype.forEach.call($checkList, item => {
                    if (!$(item).prop('checked')) {
                        flag = false
                    }
                })
                $checkAll.prop('checked',flag)
            }
        })

        $deleteAll.click(ev => {
            let arr = []
            Array.prototype.forEach.call($checkList, item => {
                if ($(item).prop('checked')) {
                    arr.push($(item).attr('userid'))
                }
            })
            if (arr.length === 0) {
                alert('当前没有选择项')
                return
            }
            let flag = confirm(`确认要删除${arr.length}条数据吗？`)
            if (!flag) return
            // 串行删除 递归
            let index = -1
            let complete = () => {
                if (index >= arr.length) {
                    alert(`批量删除成功`)
                } else {
                    alert(`已经删除${index+1}条数据，遇到问题不可以删除`)
                }
                bindHtml()
            }
            let send = async () => {
                if (index >= arr.length) {
                    complete()
                    return
                }
                let userid = arr[++index]
                let result = await axios.get('user/delete', { params: { userId: userid } })
                if (result.code != 0) {
                    complete()
                    return
                }
                send()
            }
            send()

        })
    }
    return {
        init() {
            bindDepart()
            bindHtml()
            searchHandle()
            delegate()
            selectHandle()
        }
    }
})()

userListModule.init()